<template>
  <!-- 视频流 -->
  <div class="absolute w-full h-full top-0 left-0 z-0">
    <video
      ref="bgVideo"
      class="w-full h-full"
      autoplay
      webkit-playsinline="true"
      playsinline="true"
      x5-video-player-type="h5"
      x5-video-player-fullscreen="true"
      muted
    ></video>
  </div>
  <template v-if="page === 0">
    <div class="absolute w-full h-full top-0 left-0 z-1">
      <van-image
        width="100%"
        height="100%"
        fit="fill"
        src="./ui/bg.png"
        :show-error="false"
        :show-loading="false"
      />
    </div>
    <div class="index-page w-full h-full flex items-center relative z-2">
      <div class="w-full min-h-70vh flex flex-col justify-between items-center">
        <van-image
          width="20%"
          fit="fill"
          src="./ui/LOGO.png"
          :show-error="false"
          :show-loading="false"
        />
        <div
          class="w-full min-h-40vh flex flex-col justify-center items-center"
        >
          <van-image
            width="60%"
            fit="fill"
            src="./ui/0/01.png"
            :show-error="false"
            :show-loading="false"
          />
        </div>
        <div
          class="w-full min-h-20vh flex flex-col justify-center items-center"
        >
          <van-image
            width="40%"
            fit="fill"
            src="./ui/btn04.png"
            :show-error="false"
            :show-loading="false"
            @click="page = 1"
          />
        </div>
      </div>
    </div>
  </template>
  <template v-if="page === 1">
    <!-- 输入框 -->
    <div
      v-if="pageView === 0 && showTextarea"
      class="absolute w-100vw h-33vh top-22.5vh flex justify-center"
    >
      <div class="w-33vh h-33vh z-3 flex justify-center items-center">
        <div class="w-84% h-41.5% textarea">
          <div class="h-[calc(100%-1rem)] text-11px text-#e2be8b p-2">
            <div class="h-full flex flex-col gap-1.5">
              <textarea
                ref="textareaRef"
                class="w-full h-full bg-transparent py-1 border-0"
                style="box-sizing: border-box"
                v-model="message"
                placeholder="请输入内容"
                rows="3"
                maxlength="20"
                placeholder-style="color: #e2be8b;"
                placeholder-class="text-#e2be8b"
                adjust-position="false"
                @focus="isShowBtn = false"
                @blur="isShowBtn = true"
              ></textarea>
              <div class="flex justify-between">
                <span>{{ message.length }}/20</span>
                <span @click="message = ''">清空</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 线框 -->
    <div
      class="absolute w-full h-full top-0 left-0 z-2"
      @touchstart="onTouchStart"
      @touchend="onTouchEnd"
    >
      <!-- 拍摄框 -->
      <div class="w-full">
        <div class="relative mt-8vh flex justify-center">
          <van-image
            width="94%"
            fit="fill"
            src="./ui/border.png"
            :show-error="false"
            :show-loading="false"
          />

          <!-- page3: 选择颜色渲染 -->
          <div
            v-if="pageView === 2 && !isFinished"
            class="absolute top-0 left-5% w-90% h-full"
          >
            <span
              v-for="(color, idx) in colorList"
              :key="idx"
              class="absolute"
              :style="`left: ${color.left};top: ${color.top};width: 16%`"
            >
              <van-image
                width="100%"
                fit="fill"
                class="animated2s fadeIn"
                :src="colorName === color.name ? color.imgH : color.img"
                @click="updateColor(color)"
                :show-error="false"
                :show-loading="false"
              />
            </span>
          </div>
          <!-- logo -->
          <div class="absolute top-0">
            <!-- logo -->
            <van-image
              width="25vw"
              fit="fill"
              src="./ui/LOGO.png"
              @click="updateView(1)"
              :show-error="false"
              :show-loading="false"
            />
          </div>
          <!-- 按钮 -->
          <template v-if="pageView === 0 && isShowBtn">
            <!-- 开始按钮 -->
            <div v-if="message.length > 0" class="absolute bottom-[5%]">
              <van-image
                v-if="!isInputEnd"
                width="40vw"
                fit="fill"
                src="./ui/start_h.png"
                class="animated1s fadeIn"
                @click="isInputEnd = true"
                :show-error="false"
                :show-loading="false"
              />
              <van-image
                v-else
                width="40vw"
                fit="fill"
                src="./ui/btn02.png"
                class="animated1s fadeIn"
                @click="updateView(1)"
                :show-error="false"
                :show-loading="false"
              />
            </div>
            <!-- 点击输入按钮 -->
            <div v-if="!isInputEnd" class="absolute bottom-[18%] flex gap-4">
              <van-image
                width="35vw"
                fit="fill"
                class="animated2s focusInContract"
                :src="isClickInput ? './ui/btn01.png' : './ui/btn01_n.png'"
                @click="onFocusInput"
                :show-error="false"
                :show-loading="false"
              />
              <van-image
                width="35vw"
                fit="fill"
                class="animated2s focusInContract"
                :src="isClickBless ? './ui/btn05.png' : './ui/btn05_n.png'"
                @click="setBlessingWord"
                :show-error="false"
                :show-loading="false"
              />
            </div>
          </template>
          <template v-if="pageView === 2">
            <div v-if="!isFinished" class="absolute bottom-[10%]">
              <van-image
                width="40vw"
                fit="fill"
                src="./ui/start_h.png"
                class="animated1s fadeIn"
                @click="isFinished = true"
                :show-error="false"
                :show-loading="false"
              />
            </div>
            <div
              v-else
              class="absolute bottom-[-10%] flex flex-col items-center gap-3"
            >
              <van-image
                width="10vw"
                fit="fill"
                src="./ui/tips.png"
                @click="updateView(1)"
                :show-error="false"
                :show-loading="false"
              />
              <van-image
                width="40vw"
                fit="fill"
                src="./ui/btn03.png"
                @click="updateView(1)"
                :show-error="false"
                :show-loading="false"
              />
            </div>
          </template>
        </div>
      </div>
      <!-- end -->
    </div>

    <!-- 3D部分 -->
    <div>
      <TresCanvas
        window-size
        :outputColorSpace="THREE.SRGBColorSpace"
        :toneMapping="THREE.NoToneMapping"
        :clearAlpha="0"
      >
        <TresPerspectiveCamera :position="[0, 12, 0]" :look-at="[0, 0, 0]" />

        <!-- 轴线 -->
        <TresAxesHelper />
        <!-- 网格线 -->
        <TresGridHelper :args="[10, 10]" />

        <Suspense>
          <TheExperience2
            ref="exRef"
            :craneColor="craneColor"
            :pageView="pageView"
            :isFlying="isFlying"
            @updateView="updateView"
            @showTextarea="showTextarea = true"
            @released="onFinished"
          />
        </Suspense>
      </TresCanvas>
    </div>
  </template>
</template>

<script setup lang="ts">
import * as THREE from "three";
import { onMounted, ref, shallowRef } from "vue";
import { TresCanvas } from "@tresjs/core";
import { colorList, blessingWords } from "./config";

import TheExperience2 from "./components/TheExperience2.vue";

const isShowBtn = ref(true);
const isClickBless = ref(false);
const isClickInput = ref(false);
const bgVideo = ref(null);
const textareaRef = shallowRef<HTMLTextAreaElement | null>(null);
const exRef = shallowRef<InstanceType<typeof TheExperience2> | null>(null);
const page = ref(1);
const pageView = ref(2);
const message = ref("");
const colorName = ref("yellow");
const craneColor = ref("#e7ba81");
const showTextarea = ref(false);
const isInputEnd = ref(false);
const isFinished = ref(true);
const isFlying = ref(false);
const startY = ref(0);
const endY = ref(0);

onMounted(() => {
  setVideoStream();
  // const { innerWidth, innerHeight } = window;
  // navigator.mediaDevices
  //   .getUserMedia({
  //     video: {
  //       facingMode: "environment",
  //       width: innerHeight * 2,
  //       height: innerWidth * 2,
  //     },
  //   })
  //   .then((stream) => {
  //     if (!bgVideo.value) return;
  //     bgVideo.value.srcObject = stream;
  //     // 自动播放
  //     document.addEventListener("touchstart", () => {
  //       try {
  //         bgVideo.value.play();
  //       } catch {}
  //     });
  //   })
  //   .catch(function (err) {
  //     console.log("err:", err);
  //     alert(err);
  //     /* 处理 error */
  //   });
});

function setVideoStream() {
  // 用于存储最高分辨率设备信息
  let highestResolution = 0;
  let selectedDeviceId = "";
  let selectedSetting = {};

  // 1. 获取所有视频设备
  navigator.mediaDevices
    .enumerateDevices()
    .then((devices) => {
      const videoDevices = devices.filter(
        (device) => device.kind === "videoinput"
      );

      // 2. 遍历每个视频设备
      const resolutionPromises = videoDevices.map((device) => {
        return navigator.mediaDevices
          .getUserMedia({
            video: {
              deviceId: { exact: device.deviceId },
              width: { ideal: 4096 }, // 设置较高的理想值
              height: { ideal: 2160 },
            },
          })
          .then((stream) => {
            // 3. 获取该设备的分辨率
            const track = stream.getVideoTracks()[0];
            const settings = track.getSettings();
            const resolution = settings.width * settings.height;

            // 4. 比较并记录最高分辨率
            if (resolution > highestResolution) {
              highestResolution = resolution;
              selectedDeviceId = device.deviceId;
              selectedSetting = settings;
            }

            // 停止这个设备的流
            track.stop();
            return { device, resolution };
          })
          .catch((error) => {
            console.log(`无法访问设备 ${device.label}:`, error);
            return null;
          });
      });

      return Promise.allSettled(resolutionPromises);
    })
    .then((results) => {
      // 5. 使用选中的最高分辨率设备
      // if (selectedDeviceId) {
      //   console.log(`最高分辨率设备ID: ${selectedDeviceId}`);
      // }
      const { innerWidth, innerHeight } = window;
      return navigator.mediaDevices.getUserMedia({
        video: {
          deviceId: { exact: selectedDeviceId },
          facingMode: "environment",
          width: { ideal: innerHeight }, // 设置较高的理想值
          height: { ideal: innerWidth },
          // width: { ideal: selectedSetting.width },
          // height: { ideal: selectedSetting.height },
        },
      });
    })
    .then((stream) => {
      // 使用最高分辨率摄像头的流
      bgVideo.value.srcObject = stream;
      // 自动播放
      document.addEventListener("touchstart", () => {
        try {
          bgVideo.value.play();
        } catch {}
      });
    })
    .catch((error) => {
      console.error("选择摄像头过程中出错:", error);
    });
}

const onFocusInput = () => {
  isClickInput.value = true;
  textareaRef.value?.focus();
};

const setBlessingWord = () => {
  isClickBless.value = true;
  const randomIndex = Math.floor(Math.random() * blessingWords.length);
  message.value = blessingWords[randomIndex];
};

const onFinished = () => {
  // window.location.href = `https://ar.vtogether.net/arjfqzh/#/?content=${message.value}&color=${colorName.value}`;
};

const calculateSwipe = () => {
  if (!isFinished.value) return;
  const diffY = startY.value - endY.value;

  // 设置最小滑动距离阈值
  const minSwipeDistance = 50;

  if (Math.abs(diffY) > minSwipeDistance) {
    if (diffY > 0) {
      // 向上滑动
      handleSwipeUp();
    }
  }
};

const handleSwipeUp = () => {
  console.log("handleSwipeUp...");
  isFlying.value = true;
};

const onTouchStart = (event: any) => {
  startY.value = event.touches[0].clientY;
};

const onTouchEnd = (event: any) => {
  endY.value = event.changedTouches[0].clientY;
  calculateSwipe();
};

const updateView = (view: number) => {
  pageView.value = view;
};

const updateColor = (color: any) => {
  colorName.value = color.name;
  craneColor.value = color.color;
};
</script>

<style scoped lang="less">
/* 通用写法，覆盖所有浏览器 */
::placeholder {
  color: #e2be8b;
}
</style>
